import md5 from "./md5.js"
import base64 from './base64.js'

function encode(encodeStr, salt) {
	if (!encodeStr.trim()) {
		wx.showToast({
			title: '加密内容未传！'
		})
		return
	}
	if (!salt.trim()) {
		wx.showToast({
			title: '密钥未传！'
		})
		return
	}
	let b_salt = stringToByte(md5(salt));
	let b_encodeStr = stringToByte(encodeStr);
	var buffer = new Array();
	var idx = 0;
	for (var i = 0; i < b_encodeStr.length; i++) {
		if (idx == b_salt.length) idx = 0;
		var b = b_encodeStr[i];
		buffer.push((b ^ b_salt[idx]));
		idx++;
	}
			
	return base64.fromUint8Array(new Uint8Array(buffer))
}	
			
function decode(e_string, salt) {
	if (!e_string.trim()) {
		wx.showToast({
			title: '解密内容未传！'
		})
		return
	}
	if (!salt.trim()) {
		wx.showToast({
			title: '密钥未传！'
		})
		return
	}
	let encodeStr = e_string;
	let b_salt = stringToByte(md5(salt));
	let b_encodeStr = base64.toUint8Array(e_string);
	var buffer = new Array();
	var idx = 0;
	for (var i = 0; i < b_encodeStr.length; i++) {
		if (idx == b_salt.length) idx = 0;
		var b = b_encodeStr[i];
		buffer.push((b ^ b_salt[idx]));
		idx++;
	}
	return byteToString(new Uint8Array(buffer));
}

			
function stringToByte(str) {  
	var bytes = new Array();  
	var len, c;  
	len = str.length;  
	for(var i = 0; i < len; i++) {  
		c = str.charCodeAt(i);  
		if(c >= 0x010000 && c <= 0x10FFFF) {  
			bytes.push(((c >> 18) & 0x07) | 0xF0);  
			bytes.push(((c >> 12) & 0x3F) | 0x80);  
			bytes.push(((c >> 6) & 0x3F) | 0x80);  
			bytes.push((c & 0x3F) | 0x80);  
		} else if(c >= 0x000800 && c <= 0x00FFFF) {  
			bytes.push(((c >> 12) & 0x0F) | 0xE0);  
			bytes.push(((c >> 6) & 0x3F) | 0x80);  
			bytes.push((c & 0x3F) | 0x80);  
		} else if(c >= 0x000080 && c <= 0x0007FF) {  
			bytes.push(((c >> 6) & 0x1F) | 0xC0);  
			bytes.push((c & 0x3F) | 0x80);  
		} else {  
			 bytes.push(c & 0xFF);  
		}  
	}  
	return bytes;  	
}
			
function byteToString(arr) {  
    if(typeof arr === 'string') {  
        return arr;  
    }  
    var str = '',  
        _arr = arr;  
    for(var i = 0; i < _arr.length; i++) {  
        var one = _arr[i].toString(2),  
            v = one.match(/^1+?(?=0)/);  
        if(v && one.length == 8) {  
            var bytesLength = v[0].length;  
            var store = _arr[i].toString(2).slice(7 - bytesLength);  
            for(var st = 1; st < bytesLength; st++) {  
                store += _arr[st + i].toString(2).slice(2);  
            }  
            str += String.fromCharCode(parseInt(store, 2));  
            i += bytesLength - 1;  
        } else {  
            str += String.fromCharCode(_arr[i]);  
        }  
    }  
    return str;  
}  


module.exports = {
	encode: encode,
	decode: decode,
	stringToByte: stringToByte,
	byteToString: byteToString
}
